#!/usr/bin/env bash

# Copyright 2017 The Fuchsia Authors
#
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT

# Flashes new boot image (kernel+ramdisk) into a hikey960 which is in fastboot
#  mode.  Requires that the hikey be equiped with UEFI bootloader.
#  Assumes this is run from the magenta source directory.

if [ "$#" -ne 1 ]; then
	echo "Usage: hikey-efi-flash-image <uefi repo path>"
	echo "   see /docs/targets/hikey960-uefi.md for more info"
	exit 1
fi

#where the hikey repos live
HIKEY_DIR=$1

MAGENTA_DIR=.
MAGENTA_BUILD=${MAGENTA_DIR}/build-magenta-hikey960-arm64

KERNEL=${MAGENTA_BUILD}/magenta.bin-dtb
RAMDISK=${MAGENTA_BUILD}/bootdata.bin

OUT_IMAGE=${MAGENTA_BUILD}/boot.img
DTB_FILE=${MAGENTA_DIR}/kernel/target/hikey960/device-tree.dtb
DT_IMAGE=${MAGENTA_BUILD}/dt.img

MEMBASE=0x00000000
KERNEL_OFFSET=0x00080000
RAMDISK_OFFSET=0x07c00000
DT_OFFSET=0x07a00000

CMDLINE="TERM=uart"

# mkdtimg and mkbootimg can be found at:
#  https://github.com/96boards-hikey/tools-images-hikey960/tree/master/build-from-source

${HIKEY_DIR}/tools-images-hikey960/build-from-source/mkbootimg --kernel $KERNEL \
--kernel_offset $KERNEL_OFFSET \
--base $MEMBASE \
--ramdisk_offset $RAMDISK_OFFSET \
--ramdisk $RAMDISK \
--tags_offset $DT_OFFSET \
--cmdline $CMDLINE \
-o $OUT_IMAGE || exit 1

fastboot flash boot $OUT_IMAGE || exit 1
# Can't guarantee that the target has written image
#  to flash before the fastboot command completes, so
#  short delay here before reboot.
sleep 1
fastboot reboot || exit 1
